
/*
 * @features: 滑动组件监听
 * @description: 监听路径为3个路径，第一个为最小值，第二个为变化值（2者之间），第三个为最大值
 * @Date: 2021-09-07 22:23:15
 * @Author: judu233(769471424@qq.com)
 * @LastEditTime: 2021-10-04 16:33:35
 * @LastEditors: judu233
 */
import { _decorator, error, Slider } from "cc";
import { ProxyOb } from "./Core/ProxyOb";
import VmBase from "./Core/VmBase";

const { ccclass, property, menu } = _decorator;

@ccclass(`VmProgressParme`)
class VmProgressParme {

    @property({ displayName: `是否取整`, })
    isInt = true;
}

@ccclass(`VmProgress`)
@menu('VM/VM-Progress')
export default class VmProgress extends VmBase {
    /**代理对象 */
    proxy: ProxyOb<Slider>['proxy'];

    @property(VmProgressParme)
    parmeSet = new VmProgressParme();

    /**滑动范围 */
    rageValue = 0;

    checkCanWatch() {
        if (this.watch.pathArr.length < 3) {
            console.error('VMProgress组件需要3个以上的参数');
            return false;
        }
        return super.checkCanWatch();
    }

    onDataInit() {
        try {
            //启用双向监听的话，注册滑动事件监听
            if (this.watch.controller) {
                this.node.on('slide', this.sliderChange, this);
                this.proxyOb.isCheckValue = false;
            }
            //解析并设置
            this.watch.pathArr.forEach((v, i) => this.watch.templateValueArr[i] = ProxyOb.getValue(v, 0));

            let min = Math.abs(this.watch.templateValueArr[0]);
            let max = Math.abs(this.watch.templateValueArr[2]);
            if (this.watch.templateValueArr[0] < 0)
                this.rageValue = min + max;
            else
                this.rageValue = max - min;
            let value = (this.watch.templateValueArr[1] + min) / this.rageValue;
            this.setComponentValue(value);
        } catch (err) {
            error(`节点：${this.node.name}组件的VmProgress组件init失败`);
            error(err);
        }
    }

    /**滑动轴改变 */
    sliderChange(slider: Slider) {
        //通知这个节点上的代理对象
        this.proxy.progress = slider.progress;
    }

    /**监听组件值发生变动 */
    onComponentChange(newValue, oldValue) {
        let value = newValue * this.rageValue;
        value = this.parmeSet.isInt ? Math.round(value) : value;
        value += this.watch.templateValueArr[0];
        if (Number.isNaN(value))
            value = 0;
        ProxyOb.setValue(this.watch.pathArr[1], value);
    }

    /**监听的数值发生变化 */
    onDataChange(n, o, path: string) {
        if (!this.watch.useMultipathMode) return;
        //寻找缓存位置
        let index = this.watch.pathArr.findIndex(v => v === path);
        if (index >= 0) {
            //如果是所属的路径，就可以替换文本了
            this.watch.templateValueArr[index] = n * this.rageValue;
        }

        let value = (this.watch.templateValueArr[1] + Math.abs(this.watch.templateValueArr[0])) / this.rageValue;
        if (value > 1) value = 1;
        if (value < 0 || Number.isNaN(value)) value = 0;

        this.setComponentValue(value);
    }
}
